package com.ywang.puremvc.impl;

import java.util.ArrayList;

import com.ywang.puremvc.framework.ICommand;
import com.ywang.puremvc.framework.INotification;

/**
 * @author ywang
 */
public class MacroCommand implements ICommand {
    
    INotification notification;
    private ICommand currentCommand;
    private ArrayList<ICommand> toDoList = new ArrayList<ICommand>();
    
    private boolean canceled;
    private boolean ignoreError = true;
    
    public void addSubCommand(ICommand command) {
        toDoList.add(command);
    }
    
    @Override
    public void appendNotification(INotification notification) {
        this.notification = notification;
    }

    @Override
    public int execute() {
        int type = TYPE_NO;
        while (!canceled && toDoList.size() > 0) {
            currentCommand = toDoList.get(0);
            toDoList.remove(0);
            if (type == currentCommand.getType() || type == TYPE_NO) {
                type = currentCommand.getType();
                currentCommand.appendNotification(notification);
                int result = currentCommand.execute();
                if (!ignoreError && result != OK)
                    return result;
            }
            else {
                Controller.getInstance().executeCommand(this);
                break;
            }
        }
        currentCommand = null;
        return canceled ? CANCELED : OK;
    }

    @Override
    public void cancel() {
        canceled = true;
        if (currentCommand != null)
            currentCommand.cancel();
    }

    @Override
    public void setType(int type) {
        // do nothing
    }

    @Override
    public int getType() {
        if (toDoList.size() > 0)
            return toDoList.get(0).getType();
        return TYPE_NO;
    }
}
